//
//  FLMainViewController.swift
//  swift_learning
//
//  Created by aron on 2017/1/16.
//  Copyright © 2017年 arons. All rights reserved.
//

import UIKit

class FLMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 初始化子ViewController
        initViewControllers()
        
        // 初始化Button
        initComposeButton()
        
        // 使用文件初始化
        // _initViewControllers()
    }
    
    private func initViewControllers() {
        self.addChildViewController(HomeViewController(), title: "首页", image: "tabbar_home")
        self.addChildViewController(MessageViewController(), title: "消息", image: "tabbar_message_center")
        self.addChildViewController(MessageViewController(), title: "", image: "tabbar_message_center", isUserinteraction: false)
        self.addChildViewController(DiscoveryViewController(), title: "发现", image: "tabbar_discover")
        self.addChildViewController(ProfileViewController(), title: "我", image: "tabbar_profile")
    }
    
    private func initComposeButton() {
        let composeBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 44));
        composeBtn.center = CGPoint(x: tabBar.center.x, y: tabBar.frame.size.height/2);
        composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        composeBtn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted)
        composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        composeBtn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted)
        composeBtn.addTarget(self, action: #selector(FLMainViewController.onCompostBtnClick), for: .touchUpInside)
        tabBar.addSubview(composeBtn)
    }
    
    private func addChildViewController(_ childVC: UIViewController, title: String, image: String, isUserinteraction: Bool = true) {
        childVC.title = title;
        childVC.tabBarItem.image = UIImage(named: image)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        childVC.tabBarItem.selectedImage = UIImage(named: image + "_highlighted")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        childVC.tabBarItem.isEnabled = isUserinteraction
        let navChildVC =  UINavigationController(rootViewController: childVC)
        addChildViewController(navChildVC)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
   
}

extension FLMainViewController {
    // MARK: - ......::::::: UI action :::::::......
    @objc public func onCompostBtnClick() {
        print("====onCompostBtnClick====")
        let compostVC = ComposeViewController()
        let compostNVC = UINavigationController(rootViewController: compostVC)
        present(compostNVC, animated: true, completion: nil)
    }
}

extension FLMainViewController {
    public func _initViewControllers() {
        
        // 1、获取JSONURL
        guard let url = Bundle.main.url(forResource: "MainVCSettings.json", withExtension: nil)else {
            return;
        }
        
        // 获取JSON Data ,throws 异常需要处理
// swift 中提供了三种方法处理异常
// 1、try,手动处理异常
//        do {
//           let jsonData = try Data(contentsOf: url)
//        } catch err {
//            print(err)
//        }

// 2、try? 方式，系统帮助我们处理异常如，果该出现异常，返回nil,如果没有异常，返回对应对象
//        guard let jsonData1 = try? Data(contentsOf: url) else {
//            return;
//        }

// 3、try! 方式，直接告诉系统该方法没有异常，如果出现了异常程序会崩溃！！，不建议使用
//        let jsonData2 = try! Data(contentsOf: url)
        
        
        guard let jsonData = try? Data(contentsOf: url) else {
            return;
        }
        
        // 获取JSON对象
        guard let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) else {
            return;
        }
        
        // 遍历JSON对象  let jsonArr = jsonObj as?
        guard let jsonArr = jsonObj as? [[String: AnyObject]] else {
            return;
        }
        
        for dict in jsonArr {
            BMLOG(dict)
            
            guard let imageName = dict["imageName"] as? String else {
                continue
            }
            
            guard let title = dict["title"] as? String else {
                continue
            }

            guard let vcName = dict["vcName"] as? String else {
                continue
            }

            _addChildViewController(vcName, title: title, image: imageName)
        }
    }
    
    public func _addChildViewController(_ childVCName: String, title: String, image: String) {
        // CFBundleExecutable
        guard let nameSpace = Bundle.main.infoDictionary?["CFBundleExecutable"] as? String else {
            return;
        }
        
        guard let childVCClass = NSClassFromString(nameSpace+"."+childVCName) else {
            return;
        }
        
        guard let childVCType = childVCClass as? UIViewController.Type else {
            return;
        }
        
        let childVC = childVCType.init()
        
        childVC.title = title;
        childVC.tabBarItem.image = UIImage(named: image)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        childVC.tabBarItem.selectedImage = UIImage(named: image + "_highlighted")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        let navChildVC =  UINavigationController(rootViewController: childVC)
        addChildViewController(navChildVC)
    }
}
